<template>
  <div>
    <el-form
      :rules="ischange ? updaterules: rules"
      ref="seditForm"
      :model="spojo"
      label-width="130px"
      label-position="right"
    >
      <el-form-item label="药材名称：" prop="mName">
        <!-- autocomplete="off"为 保存之前填过的值 -->
        <el-input v-model="spojo.mName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药材拉丁名称：" prop="mLatinName">
        <el-input v-model="spojo.mLatinName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="基源名称：" prop="mOriginName">
        <el-input type="textarea" v-model="spojo.mOriginName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="基源拉丁名：" prop="mOriginLatinName">
        <el-input type="textarea" v-model="spojo.mOriginLatinName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药用部位：" prop="mMethod">
        <el-input type="textarea" v-model="spojo.mMethod" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="基源简介：" prop="mOriginInterview">
        <el-input type="textarea" v-model="spojo.mOriginInterview" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药材简介：" prop="mRemarks">
        <el-input type="textarea" v-model="spojo.mRemarks" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="药材图片：" prop="imgPath">
        <el-upload
          ref="uploadImage"
          class="upload-demo"
          action="none"
          :on-change="checkType"
          accept="image/jpeg, image/jpg, image/png"
          :auto-upload="false"
          :on-remove="handleRemove"
          :file-list="fileList"
          list-type="picture"
        >
          <el-button @click="cleanImg" style="margin-top:10px" size="small" type="primary">选择图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="基源图片：" prop="mOriginImgPath">
        <el-upload
          class="upload-demo"
          action="none"
          :on-change="checkOriginType"
          accept="image/jpeg, image/jpg, image/png"
          :auto-upload="false"
          :on-remove="handleRemove"
          :file-list="fileListOrigin"
          list-type="picture"
        >
          <el-button
            @click="cleanOriginImg"
            style="margin-top:10px"
            size="small"
            type="primary"
          >选择图片</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过1M</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="价格链接：" prop="mPriceLink">
        <el-input type="textarea" v-model="spojo.mPriceLink" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import medicinalApi from "@/api/medicinal";
import uuidv4 from "uuid/v4";
import qs from "qs";

export default {
  name: "add-new",
  props: {
    addnewData: {
      type: Object
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      spojo: {
        mName: "",
        mLatinName: "",
        mOriginName: "",
        mOriginLatinName: "",
        mMethod: "",
        mOriginInterview: "",
        mRemarks: "",
        imgPath: "",
        imgPathOut: "",
        mOriginImgPath: "",
        imgOriginPathOut: "",
        mPriceLink: ""
      },
      // 用于存放图片的uuid
      uploadpic: {
        imgname: ""
      },
      ischange: null,
      rules: {
        // 更新校验规则
        mName: [
          { required: true, message: "药材名称不能为空", trigger: "blur" }
        ],
        mOriginName: [
          { required: true, message: "基源名称不能为空", trigger: "blur" }
        ],
        imgPath: [
          { required: true, message: "药材图片不能为空", trigger: "blur" }
        ]
      },
      updaterules: {
        // 校验规则
        mName: [
          { required: true, message: "药材名称不能为空", trigger: "blur" }
        ],
        mOriginName: [
          { required: true, message: "基源名称不能为空", trigger: "blur" }
        ]
      },
      fileList: [],
      fileListOrigin: [],
      headImgFile: null,
      headOriginImgFile: null
    };
  },

  created() {
    // console.log("测试生成uuid",uuidv4().replace(/-/g,""))
  },

  watch: {
    isEdit: {
      immediate: true,
      handler(val) {
        // 将isEdit的值赋给ischange，判断是新增还是更新
        this.ischange = val;
      }
    },
    addnewData: {
      immediate: true,
      handler(val) {
        this.spojo = val;
      }
    }
  },

  mounted() {
    this.$emit("update:addnewData", this.spojo);
    this.cancelFieldValidate("seditForm");
  },

  methods: {
    // 校验表单
    validateForm() {
      // 提交药材图片
      let imgfile = new FormData();
      let imgPath = uuidv4().replace(/-/g, "");
      if (this.headImgFile) {
        this.spojo.imgPath =
          imgPath +
          "." +
          this.headImgFile.name.substring(
            this.headImgFile.name.lastIndexOf(".") + 1
          );
        imgfile.append("file", this.headImgFile.raw);
        imgfile.append("imgname", imgPath);
        // console.log(imgFile.get("file"))
        // console.log(imgFile.get("imgname"))
        // console.log(qs.stringify(imgfile))
      }

      // 提交基源图片
      let originImgFile = new FormData();
      let mOriginImgPath = uuidv4().replace(/-/g, "");
      if (this.headOriginImgFile) {
        this.spojo.mOriginImgPath =
          mOriginImgPath +
          "." +
          this.headOriginImgFile.name.substring(
            this.headOriginImgFile.name.lastIndexOf(".") + 1
          );
        originImgFile.append(
          "file",
          this.headOriginImgFile.raw,
          this.headOriginImgFile.name
        );
        originImgFile.append("imgname", mOriginImgPath);
      }

      this.$refs["seditForm"].validate(valid => {
        if (valid) {
          // 提交表单
          // 提交药材图片
          // medicinalApi.uploadImg(imgfile).then(resp => {
          //   if (resp.data.flag != true) {
          //     // 失败
          //     this.$message({
          //       message: "上传药材图片失败",
          //       type: "warning"
          //     });
          //   }
          // });
          if (this.headImgFile) {
            this.$ajax({
              method: "post",
              url: "/zy-api/item/medicinal/medicinalimg",
              data: imgfile,
              headers: {
                token: this.$store.state.user.token
              }
            }).then(resp => {
              if (resp.data.flag != true) {
                // 失败
                this.$message({
                  message: "上传药材图片失败",
                  type: "warning"
                });
              }
            });
          }
          // 提交基源图片
          // medicinalApi.uploadImg(originImgFile).then(resp => {
          //   if (resp.data.flag != true) {
          //     // 失败
          //     this.$message({
          //       message: "上传基源图片失败",
          //       type: "warning"
          //     });
          //   }
          // });
          if (this.headOriginImgFile) {
            this.$ajax({
              method: "post",
              url: "/zy-api/item/medicinal/medicinalimg",
              data: originImgFile,
              headers: {
                token: this.$store.state.user.token
              }
            }).then(resp => {
              if (resp.data.flag != true) {
                // 失败
                this.$message({
                  message: "上传药材图片失败",
                  type: "warning"
                });
              }
            });
          }

          if (this.ischange) {
            console.log(JSON.stringify(this.spojo));
            medicinalApi.medicinalUpdate(this.spojo).then(resp => {
              if (resp.data.flag) {
                // 修改成功，刷新列表数据
                this.$message({
                  message: "修改药材信息成功",
                  type: "success"
                });
                // 调用父组件的查询方法，刷新数据
                this.$emit("fselect");
                // 关闭
                this.$emit("close");
              } else {
                // 失败
                this.$message({
                  message: "修改药材信息失败",
                  type: "warning"
                });
              }
            });
          } else {
            console.log(JSON.stringify(this.spojo));
            medicinalApi.medicinalInsert(this.spojo).then(resp => {
              if (resp.data.flag) {
                // 新增成功，刷新列表数据
                this.$message({
                  message: this.isEdit
                    ? "修改药材信息成功"
                    : "新增药材信息成功",
                  type: "success"
                });
                // 调用父组件的查询方法，刷新数据
                this.$emit("fselect");
                // 关闭
                this.$emit("close");
              } else {
                // 失败
                this.$message({
                  message: this.isEdit
                    ? "修改药材信息失败"
                    : "新增药材信息失败",
                  type: "warning"
                });
              }
            });
          }
        } else {
          this.$message({
            message: "提交表单失败",
            type: "warning"
          });
          return false;
        }
      });
    },

    // 清空校验
    cancelFieldValidate(formName) {
      // 清空已选的图片
      this.cleanImg();
      this.cleanOriginImg();
      this.$refs[formName].clearValidate();
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);
    },

    // 上传之前判断图片信息
    checkType(file, fileList) {
      // const isJPG = file.type === "image/jpeg";
      // const isPNG = file.type === "image/png";
      // 截取文件类型
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
        this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      // 确认要上传的文件
      // 确认要上传的文件
      this.headImgFile = file;
      console.log("选择的图片" + this.headImgFile.name);
    },

    checkOriginType(file, fileListOrigin) {
      // const isJPG = file.type === "image/jpeg";
      // const isPNG = file.type === "image/png";
      // 截取文件类型
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (fileType !== "jpeg" && fileType !== "jpg" && fileType !== "png") {
        this.$message.error("上传头像图片只能是 JPG 或 PNG格式!");
        return false;
      }
      if (!isLt1M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
        return false;
      }
      // return isJPG && isLt1M;
      // 确认要上传的文件
      this.headOriginImgFile = file;
      console.log("选择的图片" + this.headOriginImgFile.name);
    },

    // 清除之前选择的图片，确保只上传一个图片
    cleanImg() {
      this.fileList = [];
    },

    cleanOriginImg() {
      this.fileListOrigin = [];
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>